package com.example.springbootmail.utils;

import com.example.springbootmail.bean.MailBean;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import org.springframework.util.StringUtils;

import javax.mail.internet.MimeMessage;
import java.io.File;
import java.util.HashMap;
import java.util.Map;

/**
 * @author: xulinyi
 * @create: 2019-03-22 09:25
 **/
@Component
public class MailUtil {
    @Autowired
    private JavaMailSender javaMailSender;
    @Autowired
    private Configuration configuration;

    private Logger logger = LoggerFactory.getLogger(MailUtil.class);

    /**
     * 发送简单格式的邮件
     * @param mailBean
     */
    public void sendSimpleMail(MailBean mailBean) {
        try {
            SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
            //邮件发送人
            simpleMailMessage.setFrom(mailBean.getSenderUser());
            //邮件接收人
            simpleMailMessage.setTo(mailBean.getToUsers());
            if(!StringUtils.isEmpty(mailBean.getCcUsers())){
                //抄送人，使用Cc还是Bcc大家根据具体场景自己选择
                simpleMailMessage.setCc(mailBean.getCcUsers());

            }
            if(!StringUtils.isEmpty(mailBean.getBccUsers())){
                //秘密抄送（发件人，收件人，抄送人都不会看到抄送给谁了）
                simpleMailMessage.setBcc(mailBean.getBccUsers());
            }
            //邮件主题
            simpleMailMessage.setSubject(mailBean.getSubject());
            //邮件内容
            simpleMailMessage.setText(mailBean.getContent());

            javaMailSender.send(simpleMailMessage);
        } catch (Exception e) {
            logger.error("发送失败", e.getMessage());
        }
    }

    /**
     * 发送HTML格式的邮件
     * @param mailBean
     */
    public void sendHTMLMail(MailBean mailBean) {
        try {
            MimeMessage mimeMailMessage = javaMailSender.createMimeMessage();
            MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMailMessage, true);
            //发送者
            mimeMessageHelper.setFrom(mailBean.getSenderUser());
            //接收者
            mimeMessageHelper.setTo(mailBean.getToUsers());
            if(!StringUtils.isEmpty(mailBean.getCcUsers())){
                //抄送人，使用Cc还是Bcc大家根据具体场景自己选择
                mimeMessageHelper.setCc(mailBean.getCcUsers());

            }
            if(!StringUtils.isEmpty(mailBean.getBccUsers())){
                //秘密抄送（发件人，收件人，抄送人都不会看到抄送给谁了）
                mimeMessageHelper.setBcc(mailBean.getBccUsers());
            }
            mimeMessageHelper.setSubject(mailBean.getSubject());
            mimeMessageHelper.setText(mailBean.getContent(), true);
            javaMailSender.send(mimeMailMessage);
        } catch (Exception e) {
            System.out.println("发送失败："+ e.getMessage());
        }
    }

    /**
     * 发送带附件格式的邮件
     * @param mailBean
     */
    public void sendAttachmentMail(MailBean mailBean) {
        try {
            MimeMessage mimeMailMessage  = javaMailSender.createMimeMessage();
            MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMailMessage, true);
            //发送者
            mimeMessageHelper.setFrom(mailBean.getSenderUser());
            //接收者
            mimeMessageHelper.setTo(mailBean.getToUsers());
            if(!StringUtils.isEmpty(mailBean.getCcUsers())){
                //抄送人，使用Cc还是Bcc大家根据具体场景自己选择
                mimeMessageHelper.setCc(mailBean.getCcUsers());

            }
            if(!StringUtils.isEmpty(mailBean.getBccUsers())){
                //秘密抄送（发件人，收件人，抄送人都不会看到抄送给谁了）
                mimeMessageHelper.setBcc(mailBean.getBccUsers());
            }
            mimeMessageHelper.setSubject(mailBean.getSubject());
            mimeMessageHelper.setText(mailBean.getContent());
            //文件路径
            FileSystemResource file = new FileSystemResource(new File(mailBean.getFileUrl()));
            mimeMessageHelper.addAttachment(mailBean.getAttachmentFilename(), file);

            javaMailSender.send(mimeMailMessage);
        } catch (Exception e) {
            System.out.println("发送失败:"+e.getMessage());
        }
    }

    /**
     * 发送带静态资源的邮件
     * @param mailBean
     */
    public void sendInlineMail(MailBean mailBean) {
        try {
            MimeMessage mimeMailMessage  = javaMailSender.createMimeMessage();
            MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMailMessage, true);
            //发送者
            mimeMessageHelper.setFrom(mailBean.getSenderUser());
            //接收者
            mimeMessageHelper.setTo(mailBean.getToUsers());
            if(!StringUtils.isEmpty(mailBean.getCcUsers())){
                //抄送人，使用Cc还是Bcc大家根据具体场景自己选择
                mimeMessageHelper.setCc(mailBean.getCcUsers());

            }
            if(!StringUtils.isEmpty(mailBean.getBccUsers())){
                //秘密抄送（发件人，收件人，抄送人都不会看到抄送给谁了）
                mimeMessageHelper.setBcc(mailBean.getBccUsers());
            }
            mimeMessageHelper.setSubject(mailBean.getSubject());
            // 注意<img/>标签，src='cid:jpg'，'cid'是contentId的缩写，'jpg'是一个标记
            mimeMessageHelper.setText(mailBean.getContent(), true);
            // 加载文件资源，作为附件
            FileSystemResource file = new FileSystemResource(new File(mailBean.getFileUrl()));
            // 调用MimeMessageHelper的addInline方法替代成文件('jpg[标记]', file[文件])
            mimeMessageHelper.addInline(mailBean.getContentId(), file);

            javaMailSender.send(mimeMailMessage);
        } catch (Exception e) {
            logger.error("邮件发送失败", e.getMessage());
        }
    }

    /**
     * 发送基于Freemarker模板的邮件
     * @param mailBean
     * @param map 模板中传入的值
     */
    public void sendTemplateMail(MailBean mailBean,Map<String, Object> map) {
        try {
            MimeMessage mimeMailMessage = javaMailSender.createMimeMessage();
            MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMailMessage, true);
            //发送者
            mimeMessageHelper.setFrom(mailBean.getSenderUser());
            //接收者
            mimeMessageHelper.setTo(mailBean.getToUsers());
            if(!StringUtils.isEmpty(mailBean.getCcUsers())){
                //抄送人，使用Cc还是Bcc大家根据具体场景自己选择
                mimeMessageHelper.setCc(mailBean.getCcUsers());

            }
            if(!StringUtils.isEmpty(mailBean.getBccUsers())){
                //秘密抄送（发件人，收件人，抄送人都不会看到抄送给谁了）
                mimeMessageHelper.setBcc(mailBean.getBccUsers());
            }
            mimeMessageHelper.setSubject(mailBean.getSubject());
            Template template = configuration.getTemplate(mailBean.getFtlName());
            String text = FreeMarkerTemplateUtils.processTemplateIntoString(template, map);
            mimeMessageHelper.setText(text, true);
            javaMailSender.send(mimeMailMessage);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("发送失败", e.getMessage());
        }

    }


}